package com.xinyu.service;

import com.xinyu.vo.LessonDownloadToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class LessonDownloadTokenService {

    private final Map<String, LessonDownloadToken> tokenStore = new ConcurrentHashMap<>();
    private final Duration ttl;

    public LessonDownloadTokenService(@Value("${knowledge.download.token-ttl-seconds:300}") long ttlSeconds) {
        this.ttl = Duration.ofSeconds(Math.max(ttlSeconds, 60));
    }

    public LessonDownloadToken issueToken(Integer lessonId, Integer userId, String relativePath, String attachmentName) {
        cleanup();
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        Instant expireAt = Instant.now().plus(ttl);
        LessonDownloadToken payload = new LessonDownloadToken(token, lessonId, userId, relativePath, attachmentName, expireAt);
        tokenStore.put(token, payload);
        return payload;
    }

    public LessonDownloadToken consume(String token) {
        if (token == null) {
            return null;
        }
        LessonDownloadToken payload = tokenStore.remove(token);
        if (payload == null) {
            return null;
        }
        if (payload.getExpireAt().isBefore(Instant.now())) {
            return null;
        }
        return payload;
    }

    private void cleanup() {
        Instant now = Instant.now();
        tokenStore.entrySet().removeIf(entry -> entry.getValue().getExpireAt().isBefore(now));
    }
}
